﻿(function ($) {

    app.TabsInit = function(tb) {
        app.TabSw = new TabSwitcher(tb);
        app.TabSw.add( {
            tabID: 'ModVar',
            title: 'Модификации',
            init: function() {
                app.ModVar.Open('ModVar');
				app.ModVar.Resize();
				$('#ModVar').parent().bind('tabsshow', function(event, ui) {
					if (ui.panel.id == "ModVar") {
						app.ModVar.Resize();
					}
				});
            },
            show: function() {},
            hide: function() {} 
        } );
        app.TabSw.add( {
            tabID: 'SearchRes',
            title: 'Найдено',
            init: function() {
				app.ViewOptions = new ViewOptions( {
					optdlg_id: 'OptionsDlg',
					show_area_id: 'SearchRes',
					rows: 3,
					col: 5,
					sort: 'price',
//					cbfunc: function() { $('#Paginator').hide(); }
                    cbfunc: function() {
                            if( app.paginator.total == 0 ) {
                                $('#Paginator').hide(); 
                                return;
                            }
                            DoSearch('Paginator', 1);
                        }
					} );
				
				$('#ViewOptions').hide()
					.button({ icons: { primary: "ui-icon-gear"} })
					.bind('click', app.ViewOptions.ShowDialog );
            },
            show: function() {
                if( app.paginator.total > 1)  $('#Paginator').show();
				$('#ViewOptions').show();
            },
            hide: function() { 
				$('#Paginator').hide(); 
				$('#ViewOptions').hide();
			} 
        } );
		if( app.customer.uname ) {
				app.TabSw.add( {
					tabID: 'CustomerData',
					title: app.customer.uname,
					init: function() { 
							app.CarsCatalogue.Open('CustomerData');
							$('#CustomerData').parent().bind('tabsshow', function(event, ui) {
								if (ui.panel.id == "CustomerData") {
									app.CarsCatalogue.Resize();
								}
							});
					},
					show: function() {},
					hide: function() {}, 
					destroy: function() { app.CarsCatalogue.Close(); }
				} );
		}

		app.TabSw.SwitchTo('ModVar');
    }

    function ShowFoundData(rows) {
        var i, k;
        var car_id, region, modif_name, p_date, km_count, price;
        var cells = $('#SearchRes td[role="SearchRes_Unit"]');
		var geom = app.ViewOptions.GetData();

        for (i = 0; i < rows.length; i++) {
            car_id		= rows[i].cell[0];
			city_name	= rows[i].cell[1];
            modif_name	= rows[i].cell[2];
            p_date		= rows[i].cell[3];
            km_count	= rows[i].cell[4];
            price		= rows[i].cell[5];
            comment		= rows[i].cell[6];
            tbl_url		= rows[i].cell[7];
            img_url		= rows[i].cell[8];
			owner_id	= rows[i].cell[9];
            owner_name   = rows[i].cell[10];
			phone		= rows[i].cell[11];
/*			
            cells.eq(i)
                .addClass('ui-widget-content ui-corner-all')
                .html(
                '<div style="height:28px;white-space:nowrap;overflow:hidden;padding:4px;" \
                class="ui-widget-header ui-state-default ui-corner-all"><b>'+modif_name+'</b><br> \
                <span style="font-weight:normal;font-style:italic;">Регион: </span><b>'+city_name+'</b></div>'+
                '<img style="float:left;margin: 8px 4px 2px 2px;" src="'+tbl_url+'">'+
                '<table>'+
                    '<tr><td style="text-align:right;font-style:italic;">Выпуск:</td><td><b>'+p_date+'</b>г.</td></tr>'+
                    '<tr><td style="text-align:right;font-style:italic;">Пробег:</td><td><b>'+km_count+'</b> км.</td></tr>'+
                    '<tr><td style="text-align:right;font-style:italic;">Цена:</td><td><b>$'+price+'</b></td></tr>'+
                    '<tr><td style="text-align:right;font-style:italic;">Контакт:</td><td><b>'+phone+'</b></td></tr>'+
                '</table>'+
                ( comment ? '<span style="font-style:italic;">Прочее: </span><span>'+comment+'</span>' : '' )
            );
*/
            cells.eq(i)
                .addClass('ui-widget-content ui-corner-all')
                .html(
                '<div style="white-space:nowrap;overflow:hidden;padding:4px;" \
                class="ui-widget-header ui-state-default ui-corner-all"><b>'+modif_name+'</b></div> \
                <table> \
                    <tr><td>Регион:</td><td>'+city_name+'</td></tr> \
                    <tr><td>Владелец:</td><td>'+owner_name+'</td> \
                    <tr><td>Телефон:</td><td>('+phone.substr(0,3)+') '+phone.substr(3,3)+'-'+
                    phone.substr(6,2)+'-'+phone.substr(8,2)+'</td></tr> \
                </table> \
                <img style="float:left;margin: 8px 4px 2px 2px;" src="'+tbl_url+'"> \
                <table> \
                    <tr><td>Выпуск:</td><td>'+p_date+' г.</td></tr> \
                    <tr><td>Пробег:</td><td>'+km_count+' км.</td></tr> \
                    <tr><td>Цена:</td><td>$'+price+'</td></tr> \
                    <tr><td>Прочее:</td><td style="font-weight:normal;">'+comment+'</td></tr> \
                </table>'
                );
            cells.eq(i).find('td:even').addClass('app-searchres-name');
            cells.eq(i).find('td:odd').addClass('app-searchres-value');
            cells.eq(i).find('img')
                .hover(function(){ $(this).css({'cursor':'pointer'}) }, function(){ $(this).css({'cursor':'normal'}) } )
                .click( { img_id:'searchres_img_'+car_id, src:img_url, title:modif_name+' ('+owner_name+')'}, function(ev) {
                    app.ShowImage( ev.data.img_id, ev.data.src, ev.data.title );   
                });
        }
        for (k = i; k < geom.rows * geom.cols; k++) {
            cells.eq(k).html('').removeClass('ui-widget-content ui-corner-all');
        }
    }


    function DoSearch(pgID, pgNum) {
		var geom = app.ViewOptions.GetData();
        var reqData = {
            source: 'CarCatalogue',
            oper: 'find',
            page: pgNum,
            rows: geom.rows * geom.cols,
            sidx: geom.sort,
            sord: 'ASC',
            _search: true
        }

		var city_id = app.form.region.val();
        var vend = app.form.vend.val();
        var model = app.form.model.val();
        var lp_date = app.form.lp_date.val();
        var hp_date = app.form.hp_date.val();
        var lprice = app.form.lprice.val();
        var hprice = app.form.hprice.val();

		reqData.city_id = city_id;
        if (vend != '') reqData.vend_name = vend;
        if (model != '') reqData.model_name = model;
        if (lp_date != '') reqData.lp_date = lp_date;
        if (hp_date != '') reqData.hp_date = hp_date;
        if (lprice != '') reqData.lprice = lprice;
        if (hprice != '') reqData.hprice = hprice;

        $.post('callbacks.php', reqData,
                function (rsp, textStatus) {
					if( !rsp ) return;
					if (rsp.userdata.errcode) {
						if (rsp.userdata.errcode == '999') { 
							alert(rsp.userdata.errmess);
							app.customer = { uname:'', cust_id:0 };
							location.href = 'index.php'; 
						}
						else app.alert('AlertDlg', 'Ошибка', rsp.userdata.errmess, 'ipdepo-icon-stop32');
						return;
					}
                    if(!rsp.total) {
                        app.alert('AlertDlg', 'Внимание', 'Записей, соответствующих заданным условиям, не найдено', 'ipdepo-icon-info32');
//                        return;
                    }
                    
                    app.TabSw.SwitchTo('SearchRes');
                    PaginatorCB('Paginator', rsp.page, rsp.total);
                    ShowFoundData(rsp.rows);
                }, 
                'json'
        );
    }


    //        app.viewgrid = { rows: str, cols: col, sort: sort };
    function PaginatorCB(pgID, pgNum, pgTot) {
        var pgn = $('#' + pgID);
        var newpg = (pgn.find('*').length == 0) ? true : false;

        while (true) {
            if (pgTot < 2) { 
                app.paginator.current = pgNum;
                app.paginator.total = pgTot;
                pgn.hide(); 
                break; 
            }

            pgn.show();

            if (newpg ) {
//                pgn.find('*').unbind().remove();
                pgn.html(
                '<div style="width:64px; float:left">Страницы:&nbsp;</div>' +
                '<a id="' + pgID + '_m_left"></a><div id="' + pgID + '_o_left"></div>' +
                '<div class="paginator_p_wrap"><div class="paginator_p_bloc"></div></div>' +
                '<div id="' + pgID + '_o_right"></div><a id="' + pgID + '_m_right"></a>' +
                '<div class="paginator_slider" style="left:96px;"' +
                'class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">' +
                '<a class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a></div>'
                );

                $('#' + pgID + '_m_left').addClass("ui-icon ui-icon-seek-first").css({ 'float': 'left', 'cursor': 'pointer' });
                $('#' + pgID + '_o_left').addClass("ui-icon ui-icon-seek-prev").css({ 'float': 'left', 'cursor': 'pointer' });
                $('#' + pgID + '_o_right').addClass("ui-icon ui-icon-seek-next").css({ 'float': 'left', 'cursor': 'pointer' });
                $('#' + pgID + '_m_right').addClass("ui-icon ui-icon-seek-end").css({ 'float': 'left', 'cursor': 'pointer' });

                pgn.jPaginator({
                    selectedPage: pgNum,
                    nbPages: pgTot,
                    nbVisible: 5,
                    overBtnLeft: '#' + pgID + '_o_left',
                    overBtnRight: '#' + pgID + '_o_right',
                    maxBtnLeft: '#' + pgID + '_m_left',
                    maxBtnRight: '#' + pgID + '_m_right',
                    onPageClicked: function (a, num) {
                        DoSearch('Paginator', num);
                    }
                });
            }
            else
                pgn.trigger("reset", { nbPages: pgTot, nbVisible: 5, selectedPage: pgNum });

            app.paginator.current = pgNum;
            app.paginator.total = pgTot;

            pgn.css({ 'top': (pgn.parent().innerHeight() - pgn.outerHeight()) / 2 });
            break;
        }
    }

    app.SearchForm = function (formId, treeId) {
        $('#' + formId).html(' \
        <table> \
			<tr><td colspan="2"><div style="display:inline-block;"><label>Регион</label><br><select name="region"></select></div> \
			<button type="button" name="find" style="float:right;margin-top:12px;">Искать</button></td></tr> \
            <tr><td><div><label>Марка:</label></div><input name="vendor" type="text" value=""/></td> \
            <td><div><label>Модель:</label></div><input name="model" type="text" value=""/></td></tr> \
            <tr><td><div><label>Год от:</label></div><input name="lp_date" type="text" value=""/></td> \
            <td><div><label>до:</label></div><input name="hp_date" type="text" value=""/></td></tr> \
            <tr><td><div><label>Цена от:</label></div><input name="lprice" type="text" value=""/></td> \
            <td><div><label>до:</label></div><input name="hprice" type="text" value=""/></td></tr> \
        </table> \
        ');

        var form = {
			region: $('#' + formId + ' select[name="region"]'),
            vend: $('#' + formId + ' input[name="vendor"]'),
            vend_id: 0,
            vend_name: '',
            model: $('#' + formId + ' input[name="model"]'),
            model_id: 0,
            model_name: '',
            lp_date: $('#' + formId + ' input[name="lp_date"]'),
            hp_date: $('#' + formId + ' input[name="hp_date"]'),
            lprice: $('#' + formId + ' input[name="lprice"]'),
            hprice: $('#' + formId + ' input[name="hprice"]'),
            sb: $('#' + formId + ' button[name="find"]')
        };

        $.post('callbacks.php', { source: 'CarUtils', oper: 'cities' },
        function (rsp, textStatus) {
            if (rsp.errcode) {
                if (rsp.errcode == '999') { 
					alert(rsp.errmess);
					app.customer = { uname:'', cust_id:0 };
					location.href = 'index.php'; 
				}
                else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                return;
            }
			var ct = rsp.data.cities;
            for( var i=0; i<ct.length; i++ ) {
				form.region.append('<option value="'+ct[i].value+'">'+ct[i].label+'</option>');
            }
        }, 
        'json');
		
        form.sb.button({ icons: { primary: 'ui-icon-search'} });
        form.sb.bind('click', function () {
            //            PaginatorCB('Paginator', 1, 12);
            $('#Paginator').hide();
            DoSearch('Paginator', 1);
        });

        form.vend.autocomplete({
            source: function (request, responce) {
                $.post('callbacks.php', { source: 'VendorDictionary', oper: 'find', term: request.term },
                function (rsp, textStatus) {
                    if (rsp.errcode) {
                        if (rsp.errcode == '999') { 
							alert(rsp.errmess);
							app.customer = { uname:'', cust_id:0 };
							location.href = 'index.php'; 
						}
                        else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                        responce();
                        return;
                    }
                    if (rsp.data) {
                        responce($.map(rsp.data, function (item) {
                            return { label: item.name, value: item.value }
                        }));
                        return;
                    }
                    responce();
                }, 'json');
            },
            minLength: 2, autoFocus: true,
            focus: function (event, ui) { return false; },
//          focus: function (event, ui) { form.vend.val(ui.item.label); form.vend_id = ui.item.value; return false; },
            select: function (event, ui) {
                form.vend_id = ui.item.value;
                form.vend_name = ui.item.label;
                form.vend.val(ui.item.label);

                form.model_id = 0;
                form.model_name = '';
                form.model.val("");
                return false;
            }
        });
        form.vend.bind( 'keypress', function (ev) { 
            if( ev.which >= 32 ) { form.vend_id = 0; form.vend_name = ''; }
        });
        form.vend.bind( 'change', function () { 
            if( form.vend_id == 0 ) {  form.vend_name = ''; }
            form.model.val("");
            form.model_id = 0;
            form.model_name = '';             
        });
        
        form.model.autocomplete({
            source: function (request, responce) {
                $.post('callbacks.php', { source: 'ModelDictionary', oper: 'find', term: request.term, vend_id: form.vend_id },
            function (rsp, textStatus) {
                if (rsp.errcode) {
                    if (rsp.errcode == '999') { 
						alert(rsp.errmess);
						app.customer = { uname:'', cust_id:0 };
						location.href = 'index.php'; 
					}
                    else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                    responce();
                    return;
                }
                if (rsp.data) {
                    responce($.map(rsp.data, function (item) {
                        return { label: item.name, value: item.value }
                    }));
                    return;
                }
                responce();
            }, 'json');
            },
            minLength: 2, autoFocus: true,
            focus: function (event, ui) { return false; },
//          focus: function (event, ui) { form.model.val(ui.item.label); return false; },
            select: function (event, ui) {
                form.model_id = ui.item.value;
                form.model_name = ui.item.label;
                form.model.val(ui.item.label);
                return false;
            }
        });
        form.model.bind( 'keypress', function (ev) { 
            if( ev.which >= 32 ) { form.model_id = 0; form.model_name = ''; }
        });
        form.model.bind( 'change', function () { 
            if( form.model_id == 0 ) { form.model_name = ''; }
        });

        $('#' + treeId).dynatree(
        {
            autoFocus: false,
            autoCollapse: true,
            initAjax: {
                url: "callbacks.php",
                data: { node_id: "0", source: "CarTree", oper: "tree" }
            },
            onLazyRead: function (node) {
                node.appendAjax({
                    url: "callbacks.php",
                    data: { node_id: node.data.key, source: "CarTree", oper: "tree" }
                });
            },
            onActivate: function (node) {
                var subkeys = node.data.key.split('.');
                if (subkeys.length == 2) {
                    form.vend_id = subkeys[0];
                    form.vend_name = this.getNodeByKey( subkeys[0] ).data.title;
                    $('#' + formId + ' input[name="vendor"]').val(form.vend_name);
                    form.model_id = subkeys[1];
                    form.model_name = node.data.title;
                    $('#' + formId + ' input[name="model"]').val(node.data.title);
                    app.ModVar.ShowData( subkeys[1] );
					app.TabSw.SwitchTo('ModVar');
                }
                else {
                    form.vend_id = subkeys[0];
                    form.vend_name = node.data.title;
                    $('#' + formId + ' input[name="vendor"]').val(node.data.title);
                    form.model_id = 0;
                    form.model_name = "";
                    $('#' + formId + ' input[name="model"]').val("");
                }
            }        
        });

        $('a.app-treeReload').bind('click', function () {
                var tree = $('#' + treeId).dynatree("getTree");
                tree.reload();
                return false;
        })
        .hover( function() { $(this).addClass("ui-state-hover"); }, 
                function() {$(this).removeClass("ui-state-hover"); });
        app.form = form;
    }

    app.EditMenu = function (dombut) {
        var menubut = $('#' + dombut);
        var menulist = dombut + '_items';
		var tmr = 0;

        function killmenu() {
			tmr = 0;
            $('#' + dombut).unbind('mouseout', killmenu);
            $('#' + menulist).menu('destroy');
            $('#' + menulist).remove();
        };
		
        menubut.button({ icons: { primary: "ui-icon-pencil", secondary: "ui-icon-triangle-1-s"} });
        menubut.bind('click',
			function () {
				var mitems = '';
			    var exists = $('#' + menulist).length ? true : false;
			    if (exists) killmenu();
			    else {
			        $('<ul id="' + menulist + '" style="position: absolute; top: -1000px; z-index:1500;"></ul>').appendTo(document.body);

					mitems = !app.customer.uname 
					  ? '<li oper="Login"><a href="#">Вход в систему</a></li> \
						 <li oper="Register"><a href="#">Зарегистрироваться</a></li> \
						 <li oper="Restore"><a href="#">Забыл пароль</a></li>'
					  :	'<li oper="Logout"><a href="#">Выйти из системы</a></li> \
						 <li oper="Update"><a href="#">Обновить профиль</a></li>';
						 
					mitems += '<li><a href="#"><hr></hr></a></li> \
						 <li oper="IfStyle"><a href="#">Стиль интерфейса</a></li> \
						 <li oper="AdminMail"><a href="#">Написать админу</a></li>';
						 
			        $('#' + menulist).html( mitems );

			        $('#' + menulist).menu({
			            selected: function (event, ui) {
			                var oper = ui.item.attr('oper');
			                killmenu();

			                // alert(ui.item.attr('oper'));
			                switch (oper) {
								case 'Login':
									app.Customer.Login();
									break;
								case 'Register':
									app.Customer.Register();
									break;
								case 'Restore':
									app.Customer.Restore();
									break;
								case 'Logout':
									app.Customer.Logout();
									break;
								case 'Update':
									app.Customer.Update();
									break;
								case 'AdminMail':
									app.Customer.AdminMail();
									break;
								case 'IfStyle':
									app.stylesel.activate();
									break;
			                }
			            }
			        });

			        $('#' + menulist).position({ my: 'left top', at: 'left bottom', of: menubut });
                   
			        $('#' + dombut).mouseleave( function () {
						if( !tmr && $('#' + menulist).length ) tmr = setTimeout( killmenu, 200 );
					});
					$('#' + menulist).mouseenter( function() {
						if( tmr ) { clearTimeout(tmr); tmr = 0;	}
						$('#' + menulist).mouseleave( function() {
							if( !tmr && $('#' + menulist).length ) tmr = setTimeout( killmenu, 200 );
						});						
					});

			    }
			}
		);
    }

// ---------------------------------------------------------------------------
})(jQuery);
